const log4js = require('../data/log');
const logger = log4js.getLogger('info');
const http = require('http');

let httpUtils = {
    get(url, param) {
        return new Promise(function (resolve, reject) {
            if (!url) {
                reject("url不能为空");
            } else {
                if (!param) {
                    param = '';
                }
                if (url.lastIndexOf('?') === url.length - 1) {
                    url = url.substring(0, url.length - 1);
                }
                if (param.indexOf('?') === 0) {
                    param = param.substring(1, param.length);
                }

                http.get(url + '?' + param, (res) => {
                    let html = "";
                    res.on("data", (data) => {
                        html += data;
                    });
                    res.on("end", () => {
                        resolve(JSON.parse(html));
                    });
                }).on('error', (e) => {
                    logger.trace('请检查http是否启动， error=', e, 'url=', url, 'param=', param);
                    reject(e);
                });
            }
        });

    }
};

module.exports = httpUtils;
